from selenium import webdriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.microsoft import EdgeChromiumDriverManager
import time
import requests
from lxml import html

# 设置 Edge 选项
edge_options = Options()
edge_options.add_argument("--start-maximized")  # 最大化窗口
# edge_options.add_argument("--headless")  # 无头模式（不显示浏览器）

# 初始化 Edge WebDriver
driver = webdriver.Edge(service=Service(EdgeChromiumDriverManager().install()), options=edge_options)

# 你的账号和密码
USERNAME = "13824424035"
PASSWORD = "030815abcHE"

try:
    # 访问登录页面
    login_url = "https://passport.zhihuishu.com/login?service=https://onlineservice-api.zhihuishu.com/gateway/f/v1/login/gologin"
    driver.get(login_url)
    print("正在访问登录页面...")

    # 等待登录框加载（最多等10秒）
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, "input[type='text'], input[type='password']"))
    )

    # 输入账号
    username_input = driver.find_element(By.XPATH, "//input[@type='text']")
    username_input.send_keys(USERNAME)
    print("已输入账号")

    # 输入密码
    password_input = driver.find_element(By.XPATH, "//input[@type='password']")
    password_input.send_keys(PASSWORD)
    print("已输入密码")

    # 点击登录按钮
    login_button = driver.find_element(By.XPATH, '//*[@id="f_sign_up"]/div[1]/span')
    login_button.click()
    print("正在登录...")

    # 等待登录成功（检查是否跳转到新页面）
    WebDriverWait(driver, 20).until(
        lambda d: d.current_url != login_url
    )
    print("登录成功！当前页面:", driver.current_url)
    time.sleep(3)  # 等待页面加载
    # 等待考试页面元素加载并点击
    exam_element = WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((By.XPATH, '//*[@id="student-page"]/div[1]/div[4]/div/div/div/div/ul/li[2]/div'))
    )
    exam_element.click()
    print("已点击考试项目")
    time.sleep(3)  # 等待页面加载
    # 获取题目文本
    question_element = WebDriverWait(driver, 20).until(
        EC.presence_of_element_located(
            (By.XPATH, '//*[@id="app2"]/div/div[1]/div[2]/div[1]/div/div[1]/div/div/div/div/div[2]'))
    )
    question_text = question_element.text
    print("获取到的题目内容：", question_text)

except Exception as e:
    print("操作过程中出错:", e)
    # 保存截图以便调试
    driver.save_screenshot("error.png")
    print("已保存错误截图：error.png")

finally:
    # 保持浏览器打开（手动关闭）
    # driver.quit()  # 如果想自动关闭，取消注释这行
    time.sleep(3)  # 等待页面加载
    pass